package com.qinyu.treehole.interceptor;

import com.alibaba.druid.util.StringUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qinyu.treehole.annotation.UserAuth;
import com.qinyu.treehole.entities.R;
import com.qinyu.treehole.tool.TokenTool;
import com.qinyu.treehole.tool.UserTool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
public class UserAuthInterceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(handler instanceof HandlerMethod){
            HandlerMethod hm = (HandlerMethod) handler;
            UserAuth auth = hm.getMethodAnnotation(UserAuth.class);
            if(null != auth){
                String userId = request.getParameter("userId");
                String token = request.getHeader("token");

                // 1.保证token和userId有效
                if(userId == null || token == null || !StringUtils.isNumber(userId)){
                    setTokenErrorMsgToFront(response, R.no(null, UserTool.USER_TOKEN_NO_EXIST));
                    return false;
                }

                HashOperations<String, String, String> ops = stringRedisTemplate.opsForHash();
                // 2.尝试通过userId获取token，保证对应
                String userToken = ops.get(TokenTool.TOKEN_NAME, userId);

                if(userToken == null){
                    setTokenErrorMsgToFront(response, R.no(null, UserTool.USER_TOKEN_NO_EXIST));
                    return false;
                }

                // 3.尝试从token中获取时间并判断是否超时
                String timeByToken = ops.get(TokenTool.TOKEN_TIME_NAME, userToken);

                long dif = System.currentTimeMillis() - Long.valueOf(timeByToken);
                if(dif > TokenTool.TOKEN_TIME_STD){
                    // 4.token超时，把用户id指向的过期token删除
                    ops.delete(TokenTool.TOKEN_NAME, userId);
                    ops.delete(TokenTool.TOKEN_TIME_NAME, userToken);
                    setTokenErrorMsgToFront(response, R.no(null, UserTool.USER_TOKEN_TIMEOUT));
                    return false;
                }

                // 5.无意外，更新token的时间
                ops.put(TokenTool.TOKEN_TIME_NAME, userToken, String.valueOf(System.currentTimeMillis()));

                log.info("用户id:{}正在访问...token:{}....", userId, token);
            }
        }


        return true;
    }

    /**
     * 设置要向前端发送的错误信息
     * @param response
     * @param r
     * @throws IOException
     */
    private void setTokenErrorMsgToFront(HttpServletResponse response, R r) throws IOException {
        String res = objectMapper.writeValueAsString(r);
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Cache-Control", "no-cache");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        response.getWriter().println(res);
        response.getWriter().flush();
    }
}